<?php
//管理设置
namespace app\admin\controller;
use app\admin\logic\GoogleAuthenticator;
use app\admin\controller\Base;
use think\Db;
use app\common\model\SystemSet;
use app\common\model\HuiYuanSupervise;
use think\Request;
class Rbac extends Base
{
	protected $system;
	protected $huiyuan;
	public function _initialize()
	{
		parent::_initialize();
		$this->system = new SystemSet();
		$this->huiyuan = new HuiYuanSupervise();
	}
	//是否开启谷歌验证
	public function change(){
        $id = input('post.id');
        //echo $id;die;
        $id=intval($id);
        //dump($id);die;
        $res=Db::table('kkty_admin_user')->where('uid',$id)->value('googleauth');
        //dump($res);die;
        $user=Db::name('admin_user')->where('uid',$id)->find();
        if($res==1){
            $res1=Db::table('kkty_admin_user')->where('uid',$id)->update(array('googleauth'=>0));
           $this->huiyuan->caozuorizhi_xieru('账户:'.$user['nickname'].'关闭谷歌验证');
        }elseif($res==0){
            $res1=Db::table('kkty_admin_user')->where('uid',$id)->update(array('googleauth'=>1));
            $this->huiyuan->caozuorizhi_xieru('账户:'.$user['nickname'].'开启谷歌验证');
        }
        //dump($res1);die;
        if($res1==1){
            return true;
        }else{
            return false;
        }
    }
    //谷歌身份验证
    public function google(){
    	$ga = new GoogleAuthenticator();
 
		//创建一个新的"安全密匙SecretKey"
		//把本次的"安全密匙SecretKey" 入库,和账户关系绑定,客户端也是绑定这同一个"安全密匙SecretKey"
		$secret = $ga->createSecret();
		/*echo "安全密匙SecretKey: ".$secret."\n\n";*/
		 $url=$_SERVER['SERVER_NAME'];
		 
		$qrCodeUrl = $ga->getQRCodeGoogleUrl($url, $secret); //第一个参数是"标识",第二个参数为"安全密匙SecretKey" 生成二维码信息
		/*echo "Google Charts URL for the QR-Code: ".$qrCodeUrl."\n\n"; *///Google Charts接口 生成的二维码图片,方便手机端扫描绑定安全密匙SecretKey
		 
		/* 
		$oneCode = $ga->getCode($secret); //服务端计算"一次性验证码"
		echo "服务端计算的验证码是:".$oneCode."\n\n";
		 
		//把提交的验证码和服务端上生成的验证码做对比
		// $secret 服务端的 "安全密匙SecretKey"
		// $oneCode 手机上看到的 "一次性验证码"
		// 最后一个参数 为容差时间,这里是2 那么就是 2* 30 sec 一分钟.
		// 这里改成自己的业务逻辑
		$checkResult = $ga->verifyCode($secret, $oneCode, 2);
		if ($checkResult) {
		    echo '匹配! OK';
		} else {
		    echo '不匹配! FAILED';
		}*/


    	$uid = input('param.uid');
    	$uid = intval($uid);
    	$res = Db::name('googleauth')->where('uid',$uid)->find();
    	if($res){
    		js_tishi('已存在，不可重复生成','am_list');
    	}else{
    		$admin = Db::name('admin_user')->where('uid',$uid)->find();
    		$result = Db::name('googleauth')->insert(['username'=>$admin['nickname'],'secretKey'=>$secret,'httpurl'=>$qrCodeUrl,'qrcodeurl'=>$url,'uid'=>$uid]);
    		if($result){
    			$this->huiyuan->caozuorizhi_xieru('账户:'.$admin['nickname'].'生成谷歌验证码');
    			js_tishi('已生成','am_list');
    		}else{
    			js_tishi('生成失败','am_list');
    		}
    	}
    }
    //管理员谷歌身份验证信息查询
    public function am_select()
	{
		
		$id=input('post.id');
		$data=Db::name('googleauth')->where("id",$id)->find();
		 if($data['pic']==''){
		 	$content = file_get_contents("{$data['httpurl']}");
		 	$pic = 'file_'.$data['id'].'.png';
		 	file_put_contents($pic, $content);
		 	Db::name('googleauth')->where('id',$id)->update(array('pic'=>$pic));
			
		 } 
		 $data=Db::name('googleauth')->where("id",$id)->find();
		exit(json_encode($data));
	}
	//管理人员列表页面
	public function am_list()
	{
		$list = Db::name('admin_user')->alias('a')
		->join("googleauth b",'a.uid=b.uid','left')->field('a.uid as uid,nickname,secretKey,id,a.googleauth,a.name,a.time,a.ip')
		->select();
		
		$this->assign('list',$list);
		return $this->fetch();
	}
	public function am_new(){
		if( request()->isPost() ){
			$nickname = input('nickname','');
			$password = input('password','');
			$name=input('name');
			if( !empty($nickname) && !empty($password) && !empty($name) ){
				$where = array('nickname'=>input('post.nickname'),'password'=>md5(input('post.password')));
				
				$t = $this->system->dFind('admin_user',$where);
				
				if($t['uid']){
					if($t['nickname']==input('post.nickname')){
						$this->system->alertWin('账号已存在', '/admin/Rbac/am_new');
					}
				}else{
					$tem = Db::name('auth_role')->where('name','默认权限')->value('id');
					if(!$tem){
						Db::name('auth_role')->insert(['name'=>'默认权限','status'=>1,'remark'=>'新账户所默认的权限']);
						$tem = Db::name('auth_role')->where('name','默认权限')->value('id');
						
					}
					$access = Db::name('auth_access')->where('role_id',$tem)->select();
					
					if(!isset($access[0])){
						$data = [
									['role_id'=>$tem,'type'=>'admin_url','menu_id'=>99,'rule_name'=>'admin/index/index'],
									['role_id'=>$tem,'type'=>'admin_url','menu_id'=>89,'rule_name'=>'admin/statistics/tj_ptbj'],
								];
						foreach($data as $va){
							Db::name('auth_access')->insert($va);
						}
					}

					Db::name('admin_user')->insert(['name'=>$name,'nickname'=>input('nickname'),'password'=>md5(input('password'))]);
			
					$us = Db::name('admin_user')->where($where)->value('uid');
					
					Db::name('auth_role_user')->insert(['role_id'=>$tem,'user_id'=>$us]);
					$this->huiyuan->caozuorizhi_xieru('新增管理员:'.$name);
					$this->system->alertWin('新增成功', '/admin/Rbac/am_list');

				}
			}else{
				$this->system->alertWin('注册账号姓名密码不能为空', '/admin/Rbac/am_new');
			}
		}
		return $this->fetch();
	}
	
	public function am_edit()
	{
		//判断是否有修改真实姓名的权限
		$userid=input('cookie.uid');
		$user=Db::name('auth_role_user')->where('user_id',$userid)->field('role_id')->select();
		$arr='';
		foreach($user as $k=>$v){
			$arr.=$v['role_id'].',';
		}
		$arr=rtrim($arr,',');
		$array=Db::name('auth_access')->where('rule_name','admin/rbac/zhenname')->where('role_id','in',$arr)->select();
		
		if(empty($array)){
			$result=0;
		}else{
			$result=1;
		}

		$this->assign('result',$result);
		$uid = input('param.uid');
		$where = array('uid'=>$uid);
		$t=$this->system->dFind('admin_user',$where);
		$this->assign('t',$t);
		if(input('post.')){
			$arr = array();
			foreach (input('post.') as $k=>$v){
				
				if($v){$arr[$k] = $v;}
				if($k=='password' && $v!=''){$arr[$k]=md5($v);}
			}
			
			$quey = $this->system->dUpdate('admin_user',$where, $arr);
			$this->huiyuan->caozuorizhi_xieru('修改管理员信息，账号:'.$t['nickname']);
			$this->system->alertWin('更改成功', '/admin/Rbac/am_list');
		}
		return $this->fetch();
	}
	
	public function am_qxgl(){
		$t = $this->system->dLists('auth_role');

		
		$uid = input('uid');
		$where = array('user_id'=>$uid);
		$user=Db::name('admin_user')->where('uid',$uid)->find();
		$q = $this->system->dLists('auth_role_user',$where);

		foreach ($t as &$value){
			$query = Db::name('auth_role_user')->where('user_id',$uid)->where('role_id',$value['id'])->value('id');

			if($query){
				$value['check'] = 'checked';
			}else{
				$value['check'] = '';
			}
			
		}
		$this->assign('t',$t);
		if(input('post.')){
			if($q){
				foreach ($q as $v){
					$id = $v['id'];
					$wherea=array('id'=>$id);
					Db::name('auth_role_user')->where($wherea)->delete();
				}
			}
			foreach (input('post.') as $v){
				foreach ($v as $i){
					$data['role_id']=$i;
					$data['user_id'] = $uid;
					Db::name('auth_role_user')->insert($data);
				}
			}
			$this->huiyuan->caozuorizhi_xieru('修改管理员权限，账号:'.$user['nickname']);
			$this->system->alertWin('操作成功', '/admin/Rbac/am_list');
			
		}
		
		return $this->fetch();
	}
	
	public function am_delete()
	{
		$uid = input('param.uid');
		$where = array('uid'=>$uid);
		$t=$this->system->dFind('admin_user',$where);
		$this->huiyuan->memberDelete('admin_user', $where);
		$this->huiyuan->memberDelete('googleauth', $where);
		$this->huiyuan->caozuorizhi_xieru('删除管理员，账号:'.$t['nickname']);
		$this->system->alertWin('删除成功', '/admin/Rbac/am_list');
	}
	public function am_czrz()
	{
		$where=array('rz_class'=>1);
		$search = input('search','');
		if( ''!==$search ){
			$where['rz_user'] = $search;
		}
		$list = $this->huiyuan->dlSelect('rizhi_jl',$where,16);
		$this->assign('q',$list);
		$this->assign('search',$search);
		return $this->fetch();
	}
//白名单列表
	public function bmd_list()
	{

		$list = Db::name('baimingdan')->select();

		$this->assign('list',$list);
		$open=Db::name('baimingdan_open')->find();
		$this->assign('open',$open);
		return $this->fetch();
	}
//添加白名单
	public function bmd_add()
	{


		$request = Request::instance();
		$ip=$request->ip();
		$this->assign('ip',$ip);

		$username=input('cookie.user');
		$content=input('post.content');
		$beizhu=input('post.beizhu');
		if($content){
			$ips=explode(" ",$content);
			$repeatips="";//重复IP
			$wrongips="";//非合法IP
			$rightips="";//添加成功的IP;
			foreach ($ips as $k => $v) {
				if(filter_var($v, FILTER_VALIDATE_IP)) {
					$result=Db::name("baimingdan")->where('ip',$v)->find();
					if($result){
						$repeatips.=$v."  ";
					}else{
						Db::name("baimingdan")->insert(['cname'=>$username,'ip'=>$v,'time'=>time(),'beizhu'=>$beizhu]);
						$rightips.=$v."  ";
						$this->huiyuan->caozuorizhi_xieru('添加白名单，IP:'.$v);
					}
					
				}
				else {
					$wrongips.=$v."  ";
					
				}
			}

			$right=empty($rightips)?"":substr($rightips,0,strlen($rightips)-1)."添加成功";
			$repeat=empty($repeatips)?"":substr($repeatips,0,strlen($repeatips)-1)."已经在白名单中，无需重复添加";
			$wrong=empty($wrongips)?"":substr($wrongips,0,strlen($wrongips)-1)."不是合法IP，添加失败";


			$this->system->alertWin($right."\\n".$repeat."\\n".$wrong, '/admin/Rbac/bmd_list');
		}

		

		return $this->fetch();
	}
	//修改白名单
	public function bmd_edit()
	{

		$id=input('param.id');
		$result=Db::name('baimingdan')->where('id',$id)->find();

		$this->assign('result',$result);
		$beizhu=input('post.beizhu');
		$ip=input('post.content');
		$username=input('cookie.user');
		if($ip){
			$isip=Db::name('baimingdan')->where('ip',$ip)->find();
			if($isip && $isip['id']!=$id){
				$this->system->alertWin('此IP已添加过白名单，无需重复添加', '/admin/Rbac/bmd_list');
			}else{				
				$where=array('id'=>$id);
				$arr=array('ip'=>$ip,'time'=>time(),'beizhu'=>$beizhu,'cname'=>$username);
				$quey = $this->system->dUpdate('baimingdan',$where, $arr);
				$this->huiyuan->caozuorizhi_xieru('修改白名单，IP:'.$ip);
				$this->system->alertWin('更改成功', '/admin/Rbac/bmd_list');
			}

			
		}
		

		return $this->fetch();
	}
	//删除白名单
	public function bmd_delete()
	{
		$id=input('param.id');
		$where = array('id'=>$id);
		$find=Db::name('baimingdan')->where($where)->find();
		$this->huiyuan->memberDelete('baimingdan', $where);
		$this->huiyuan->caozuorizhi_xieru('删除白名单，IP:'.$find['ip']);
		$this->system->alertWin('删除成功', '/admin/Rbac/bmd_list');
		
		return $this->fetch();
	}
	//白名单是否启用
	public function isbaimingdan(){
        $id = input('post.id');
        //echo $id;die;
        $id=intval($id);
        //dump($id);die;
        $res=Db::table('kkty_baimingdan_open')->where('id',$id)->value('open');
        //dump($res);die;
        if($res==1){
            $res1=Db::table('kkty_baimingdan_open')->update(array('id'=>$id,'open'=>0));
            $this->huiyuan->caozuorizhi_xieru('白名单开关设置为:关');
        }elseif($res==0){
            $res1=Db::table('kkty_baimingdan_open')->update(array('id'=>$id,'open'=>1));
            $this->huiyuan->caozuorizhi_xieru('白名单开关设置为:开');
        }
        //dump($res1);die;
        if($res1==1){
            return true;
        }else{
            return false;
        }
    }
    public function quanxian(){
    	$id=input('id');
    	$list=Db::name('auth_access')->alias('a')->join('menu m','a.menu_id=m.id')->field('m.name')->select();
    	
    	$this->assign('t',$list);
    	return $this->fetch();
    }
}